package javamusic.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import javamusic.excepcion.DAOExcepcion;
import javamusic.modelo.Noticia;
import javamusic.util.ConexionBDKaraoke;


public class NoticiaDAO extends BaseDAO{

	
	public Noticia insertar(Noticia vo) throws DAOExcepcion {
		String query = "insert into noticia(Mensaje,fecha) values (?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBDKaraoke.obtenerConexion();
			stmt = con.prepareStatement(query);
			
			stmt.setString(1, vo.getMensaje());
			stmt.setDate(2, vo.getFecha());
			
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			// Obtener el ultimo id
			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			vo.setIdnoticia(id);

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}


	
	
	public Collection<Noticia> listar(int dias) throws DAOExcepcion {
		Collection<Noticia> c = new ArrayList<Noticia>();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBDKaraoke.obtenerConexion();
			String query = "select idnoticia,Mensaje,fecha from noticia where Date(fecha) <= Date(now()) and Date(fecha)>= adddate(Date(now()),-?)";
			stmt = con.prepareStatement(query);
			stmt.setInt(1, dias);
			
			rs = stmt.executeQuery();
			
			while (rs.next()) {
				Noticia vo = new Noticia();
				vo.setIdnoticia(rs.getInt("idnoticia"));
				vo.setMensaje(rs.getString("Mensaje"));
				vo.setFecha(rs.getDate("fecha"));
				
				c.add(vo);
			}

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return c;
	}


}
